package com.sqfw.project.utils.tsa;

import com.sqfw.project.utils.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class TsaServerUtils {

    // 172.31.44.246:8088
    static String tsaApiUrl = "http://172.31.44.246:8088/tsa-server";
    static String authCode = "2azWBrl1XU";

    static String req = "/tsa/req";

    static String verify = "/tsa/verify";


    static String info = "/tsa/info";


    public static String req(String password) {
        Map<String, String> headerParam = new HashMap<>();
        headerParam.put("charset", "UTF-8");
        Map<String, String> params = new HashMap<>(16);
        String b64Password = Base64.getEncoder().encodeToString(password.getBytes());
        params.put("body", b64Password);
        params.put("authCode", authCode);
        params.put("algId", "1");
        String apiUrl = tsaApiUrl + req + "?authCode=" + authCode + "&algId=1";
        log.info("请求url： {}", apiUrl);
        log.info("请求参数-params： {}", params.toString());
        // 调用接口
        String result = HttpClientUtils.postJson(apiUrl , params);
        log.info("时间戳请求结果： {}", result);
        Map<String, String> params2 = new HashMap<>(16);
        params2.put("timestamp", result);
        log.info("请求url2： {}", tsaApiUrl + info);
        log.info("请求参数-params2： {}", params2.toString());
        String result2 = HttpClientUtils.postJson(tsaApiUrl + info, params2);
        log.info("时间戳请求结果--result2： {}", result2);

        verify(b64Password, result);

        return null;
    }


    public static String verify(String password, String tsaPassword) {
        Map<String, String> params = new HashMap<>(16);
        String b64Password = Base64.getEncoder().encodeToString(password.getBytes());
        String tsaPassword2 = Base64.getEncoder().encodeToString(tsaPassword.getBytes());
        params.put("tsRequest", b64Password);
        params.put("tsResponse", tsaPassword2);
        log.info("验证请求url2： {}", tsaApiUrl + info);
        log.info("验证请求参数-params2： {}", params.toString());
        String apiUrl = tsaApiUrl + verify + "?authCode=" + authCode + "&algId=1";
        // 调用接口
        String result = HttpClientUtils.postJson(apiUrl , params);
        log.info("验证时间戳请求结果： {}", result);
        return null;
    }


    /**
     * 测试
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args){

        req("123456");

    }

}
